package com.jd.repairdata.common;
	import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


	public class ExcelUtils {

		/**
		 * 导入拦截金额Excel文件
		 * 
		 * @param file
		 * @param username
		 * @return
		 * @throws IOException
		 */
		public static String[][] readExcel(String filepath) throws IOException {
			FileInputStream fin = new FileInputStream(new File(filepath));
			Workbook wb = null;
			if (filepath.endsWith("xls")) {
				wb = new HSSFWorkbook(fin);
				fin.close();
			} else if (filepath.endsWith("xlsx")) {
				wb = new XSSFWorkbook(fin);
				fin.close();
			} else {
				throw new IOException("不支持的文件类型");
			}
			return readAllExcel(wb);
		}

		/**
		 * 读取导入文件内容
		 * @param wb
		 * @param username
		 * @return
		 * @throws IOException
		 */
		private static String[][]  readAllExcel(Workbook wb
				) throws IOException {
			Sheet sheet = wb.getSheetAt(0);
			int rows = sheet.getLastRowNum() - sheet.getFirstRowNum();
			int count = 0;
			for(int r = 0; r <= 20000; r++)
			{

				Row row = sheet.getRow(r);
				if (row == null) {
					break;
				}
				if (row.getCell(0) == null) {
					break;
				}else{
					count++;
				}
			}
			rows = count;
			//限制导入行数为100
			if(rows >= 200) rows = 200;
			String[][] map = new String[rows][100];
			for (int r = 1; r <= rows; r++) {
				
				Row row = sheet.getRow(r);
				if (row == null) {
					continue;
				}
				int cols = row.getLastCellNum() - row.getFirstCellNum();

				if (row.getCell(0) == null) {
					continue;
				}
				try {
					for (int c = 0; c <= cols; c++) {
						Cell cell = row.getCell(c);
						if (cell == null) {
							map[r][c] = "";
							continue;
						}
						cell.setCellType(Cell.CELL_TYPE_STRING);
						String cellValue = cell.toString();
						map[r][c] = cellValue;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return map;
		}


}
